package com.nhc.serviceapi;


import com.astrob.util.SysUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

//http://megowx.com/we7/bhcnav.php?a=regetvcodejson&deviceid=2a020d390aed0
public class ServiceApi {

    public static final String HOST = "http://hcapi.megowx.com/";
    public static final String ServiceHOST = HOST + "we7/bhcnav.php?&a=";
    public static final String REGETVCODE_URL = ServiceHOST + "regetvcodejson";


    public static void regetvcode(final String deviceid,
                                  final ServiceRequestCallBack<VcodeInfo> callBack) {
        HashMap<String, String> params = new HashMap<>();
        params.put("deviceid", deviceid);
        if (SysUtils.getInstance().is240x320) {
            params.put("status", "1");
        } else {
            params.put("status", "2");
        }

        String url = REGETVCODE_URL;
        http_post(url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String response = responseInfo.result;
                ResponseResult result = parseResponse(response);
                if (result.isOK()) {
                    try {
                        JSONTokener jsonParser = new JSONTokener(response);
                        JSONObject object = (JSONObject) jsonParser.nextValue();
                        JSONObject json = object.getJSONObject("data");
                        VcodeInfo.get().deviceid = json.getString("deviceid");
                        VcodeInfo.get().vcode = json.getString("vcode");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    callBack.onSuccess(VcodeInfo.get());
                } else {
                    callBack.onFailure(result.code, result.error);
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                callBack.onFailure(-1, "请求失败");
            }
        });
    }

    public static String digest(Map<String, String> params, String secret) {
        StringBuilder result = new StringBuilder();
        List<String> keys = new ArrayList<String>(params.keySet());// map中的参数是区分大小写的
        Collections.sort(keys);
        for (Iterator<String> iterator = keys.iterator(); iterator.hasNext(); ) {
            String key = iterator.next();
            if (!"sign".equalsIgnoreCase(key)) { // 必须这么写，set里调用remove方法，无法忽略大小写;request里的map无法remove
                result.append(key).append(params.get(key));
            }
        }
        result.append(secret);
        return MD5(result.toString());
    }

    /**
     * generate MD5
     *
     * @param src
     * @return
     * @throws Exception
     */
    public static String MD5(String src) {
        try {
            if (src == null) {
                return "";
            }
            byte[] result = null;
            MessageDigest alg = MessageDigest.getInstance("MD5");
            result = alg.digest(src.getBytes("utf-8"));
            return byte2hex(result);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    private static String byte2hex(byte[] b) {
        if (b == null) {
            return "";
        }
        StringBuffer hs = new StringBuffer();
        String stmp = null;
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                hs.append("0");
            }
            hs.append(stmp);
        }
        return hs.toString();
    }

    protected static void http_post(String url, HashMap<String, String> param, RequestCallBack<String> callback) {
        post(15000, url, param, callback);
    }

    protected static void post(int timeout, String url, HashMap<String, String> param, RequestCallBack<String> callback) {
        RequestParams params = new RequestParams();
        params.setContentType("application/x-www-form-urlencoded");
        Iterator iter = param.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = entry.getKey().toString();
            String val = entry.getValue().toString();
            params.addBodyParameter(key, val);
        }
        new HttpUtils(timeout).send(HttpRequest.HttpMethod.POST, url, params, callback);
    }

    protected static void http_get(String url, RequestCallBack<String> callback) {
        new HttpUtils().send(HttpRequest.HttpMethod.GET, url, callback);
    }

    public static class ResponseResult {
        public int code; //当code == 0时， result有效，否则error有效
        public String result;
        public String error;

        public boolean isOK() {
            return code == 0;
        }
    }

    public static ResponseResult parseResponse(String response) {
        ResponseResult result = new ResponseResult();
        try {
            JSONObject json = new JSONObject(response);
            result.code = json.getInt("code");
            if (result.code == 0) {
                result.result = json.getString("data");
            } else {
                result.error = json.getString("msg");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static class VcodeInfo extends Entity {
        private static final long serialVersionUID = 2L;
        public String deviceid = "";
        public String vcode = "";

        private static VcodeInfo vcodeInfo = new VcodeInfo();

        public static VcodeInfo get() {
            return vcodeInfo;
        }

    }

}
